<template>
  <div class="page">
    <div class="answer">
      <div class="answerLeft">
        <div style="padding-bottom: 15px; border-bottom: 1px solid #dcdfe6;">
          <el-button @click="onClickCreateChat" plain type="primary">新建会话</el-button>
        </div>
        <div @click="onClickChatItem(item)" v-for="item in chatHistory.list" :key="item.id">
          <template v-if="!item._edit">
            <div :class="['chatHistory-item', { 'is-active': item.id === chatHistory.questionId }]">
              <div class="chatHistory-item__bd">{{ item.title }}</div>
              <div class="chatHistory-item__handle">
                <i @click.stop="onClickEditTitle(item)" class="el-icon-edit modify-icon"></i>
                <el-popover
                  :ref="`popover-${item.id}`"
                  placement="top"
                  width="220" trigger="click">
                  <p class="answerLeft-deleteConfirm">删除后无法恢复，是否继续删除？</p>
                  <div style="text-align: center; margin: 0">
                    <el-button class="answerLeft-deleteConfirm__btn" @click="$refs[`popover-${item.id}`][0].doClose()">取消</el-button>
                    <el-button @click="confirmDeletion(item)" class="answerLeft-deleteConfirm__btn" type="primary">确定</el-button>
                  </div>
                  <i @click.stop slot="reference" class="el-icon-delete modify-icon"></i>
                </el-popover>
              </div>
            </div>
          </template>
          <template v-else>
            <div @click.stop :class="['chatHistory-item', { 'is-active': item.id === chatHistory.questionId }]">
              <div class="chatHistory-item__bd">
                <el-input @keydown.enter.native="saveChatTitle(item)" v-model="item._editTitle" :ref="`editTitleInput-${item.id}`" class="modify-title" maxlength="20"></el-input>
              </div>
              <div class="chatHistory-item__handle">
                <i @click.stop="saveChatTitle(item)" class="el-icon-check modify-icon"></i>
                <i @click.stop="item._edit = false" class="el-icon-close modify-icon"></i>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div class="answerMain">
        <div class="answerMain-bd">
          <div class="answerMain-item">
            <img src="@/assets/images/ai-avatar.png" class="answerMain-item__avatar" />
            <div class="answerMain-item__content">
              <span class="defaultQuestion-title">您好，我是智能小道！</span>
              作为您的智能助手，我能介绍学校，解读专业，讲解职业……能帮助您解决升学规划方面的各种问题。
              除此之外，小道还可以尝试帮助解决其他方面的问题或在您需要的时候陪您聊天！
              您可以试着问我：
              <el-row :gutter="10">
                <el-col v-for="item in defaultQuestion.list" :key="item.id" :span="12">
                  <div @click="onClickDefaultQuestion($event, item)" class="defaultQuestion-item">
                    <i class="el-icon-search modify-icon"></i>{{ item.value }}
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
          <div v-for="item in answerList" :class="['answerMain-item', {'roleUser': item.role === 'user' }]">
            <img v-show="item.role === 'assistant'" src="@/assets/images/ai-avatar.png" class="answerMain-item__avatar" />
            <img v-show="item.role === 'user'" src="@/assets/images/ai-question-avatar.png" class="answerMain-item__avatar" />
            <div class="answerMain-item__content">{{ item.content }}</div>
          </div>
          <div v-if="submitLoading" class="answerMain-item">
            <img src="@/assets/images/ai-avatar.png" class="answerMain-item__avatar" />
            <div class="answerMain-item__content">
              <i class="el-icon-loading"></i>
            </div>
          </div>
        </div>
        <div class="answerMain-ft">
          <div class="answerMain-input">
            <el-input v-model.trim="answerKeyword" @keydown.enter.native="onSubmit" placeholder="请输入问题，可通过shift+回车换行" spellcheck="false" class="answerMain-input__textarea" type="textarea"></el-input>
            <el-button icon="el-icon-s-promotion" @click="onSubmit" :loading="submitLoading" type="primary" class="answerMain-input__button">

            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      defaultQuestion: {
        list: [
          { id: 1, value: '西安交通大学怎么样？', },
          { id: 2, value: '统计学专业就业好不好？', },
          { id: 3, value: '产品经理职业需要具备什么技能？', },
          { id: 4, value: '汉语言与汉语言文学专业有什么区别？', },
        ]
      },
      submitLoading: false,
      answerKeyword: undefined,
      answerList: [],
      // 聊天历史记录
      chatHistory: {
        list: [],
        questionId: undefined,
      }
    }
  },
  created() {
    this.getBaiduAIChatList()
  },

  methods: {
    onClickCreateChat() {
      if (this.chatHistory.list.length >= 10) {
        return this.$message.error('您最多可同时建立10个对话，如需新建对话，请先删除会话！')
      }
      this.chatHistory.questionId = undefined
      this.answerList = []
      this.answerKeyword = undefined
    },
    onClickEditTitle(item) {
      this.chatHistory.list.map(item => item._edit = false)
      item._edit = true
      this.$nextTick(() => {
        this.$refs[`editTitleInput-${item.id}`][0].focus()
      })
    },

    saveChatTitle(item) {
      this.$api.updateBaiduAIChatTitle({
        id: item.id,
        title: item._editTitle
      }).then(res => {
        if (![0, 200].includes(res.code)) {
          return this.$message.error(res.msg)
        }
        this.$message.success('修改成功')
        this.getBaiduAIChatList()
      })

    },
    confirmDeletion(item) {
      this.$api.deleteBaiduAIChat({ id: item.id }).then(res => {
        if (![0, 200].includes(res.code)) {
          return this.$message.error(res.msg)
        }
        this.$message.success('删除成功')
        this.getBaiduAIChatList()
      })
    },
    onClickDefaultQuestion(event, item) {
      this.answerKeyword = item.value
      this.onSubmit(event)
    },

    getBaiduAIChatList() {
      this.$api.queryBaiduAIChatList().then(res => {
        if (![0, 200].includes(res.code)) {
          return this.$message.error(res.msg)
        }
        res.data.map(item => {
          item._edit = false
          item._editTitle = item.title
          return item
        })
        this.chatHistory.list = res.data
      })
    },

    onClickChatItem(item) {
      this.chatHistory.questionId = item.id
      this.answerList = item.itemList

      this.$nextTick(() => {
        let elem = document.querySelector('.answerMain-bd')
        elem.scrollTop = elem.scrollHeight
      })
    },


    onSubmit(event) {
      if (this.answerList.length >= 30) {
        return this.$message.error('每个对话窗口最多可提30个问题，超过该限额请新建对话窗口。')
      }
      if (event.keyCode === 13) {
        event.preventDefault(); // 阻止默认行为，即回车换行
        if (event.shiftKey) {
          this.answerKeyword += "\n";
        }
      }
      if (!this.answerKeyword) {
        return this.$message.warning('请输入内容')
      }
      if (this.submitLoading) return
      this.submitLoading = true
      this.answerList.push({
        role: 'user',
        content: this.answerKeyword
      })
      this.answerKeyword = undefined
      this.$nextTick(() => {
        let elem = document.querySelector('.answerMain-bd')
        elem.scrollTop = elem.scrollHeight
        // window.scrollTo(0, document.body.scrollHeight)
      })


      this.$api.getBaiduAIAnswerV2({
        questionId: this.chatHistory.questionId,
        list: this.answerList.slice(-30),
      }).then(res => {
        console.log('getBaiduAIAnswerV2', res);
        if (![0, 200].includes(res.code)) {
          return this.$message.error(res.msg)
        }
        if (!this.chatHistory.questionId) {
          this.getBaiduAIChatList()
          this.chatHistory.questionId = res.data.questionId
        }
        this.answerList.push({
          role: 'assistant',
          content: res.data.content
        })
        this.submitLoading = false
        this.$nextTick(() => {
          let elem = document.querySelector('.answerMain-bd')
          elem.scrollTop = elem.scrollHeight
          // window.scrollTo(0, document.body.scrollHeight)
        })
      })
    }
  },
}
</script>

<style lang="stylus" scoped>
.modify-icon
  display inline-block
  font-size 14px
  padding 5px
  cursor pointer
  &:hover
    background: #e1e5fa;
    border-radius: 4px;
    color PrimaryColor

.page
  background: #F9F9F9;
.defaultQuestion
  &-title
    color: #05073b;
    font-size: 26px;
    font-weight: 600;
    line-height: 36px;
    margin-bottom: 8px;
  &-item
    padding 16px
    background: #f6f8fd;
    border-radius: 6px;
    margin-top 10px
    cursor pointer
    font-size 16px
    font-weight 600
    .modify-icon
      font-size 16px
    .modify-icon:hover
      background: unset;

    &:hover
      background: #e9ecfb;
      color PrimaryColor
.answer
  display flex
  justify-content: center;
  height 100%
  padding 10px
  box-sizing border-box
  &Left
    width 280px
    margin-right 10px
    background linear-gradient(180deg, #f5f4f6, #e6ebf7);
    border-radius: 8px;
    padding: 15px 10px 0 10px;
    &-deleteConfirm
      padding 12px 0
      text-align center
      &__btn
        width 92px
        height 32px
        line-height 32px
        padding 0 4px

  &Main
    padding-top 9px;
    font-size: 15px;
    display flex
    flex-direction: column;
    background linear-gradient(180deg, #f5f4f6, #e6ebf7);
    width 900px
    border-radius: 8px;
    &-bd
      flex-grow: 1;
      // flex-basis: 0%;
      height: 0;
      overflow-y: auto;
      flex-direction: column;
      display: flex;
      uiBlock();
      background unset
      box-sizing border-box
      /* 滚动条滑块 */
      &::-webkit-scrollbar-thumb {
        border-radius: 4px;
        background: rgba(108, 119, 143, 0.3);
      }
      &::-webkit-scrollbar {
        height: 20px;
        width: 4px;
      }
    &-ft
      flex-shrink: 0;
      min-height: 50px;
      padding: 12px 82px 30px 82px;
      box-sizing border-box


.chatHistory-item
  display: flex;
  align-items: center;
  padding: 0 10px 0 0;
  margin-top: 10px;
  &:hover, &.is-active
    background: rgba(255, 255, 255, .9);
    border-radius: 8px;
    box-shadow: 0 16px 20px 0 rgba(173, 167, 224, .06);
    color: initial;
  &:hover
    .chatHistory-item__handle
      display block
  &__hd
    flex-shrink 0
  &__bd
    flex 1
    color: #000c3f;
    cursor: pointer;
    font-size: 14px;
    font-weight: 400;
    height: 50px;
    line-height: 50px;
    overflow: hidden;
    padding: 0 10px 0 10px;
    position: relative;
    text-align: justify;
    text-overflow: ellipsis;
    white-space: nowrap;
  &__handle
    flex-shrink 0
    display none
.answerMain-item
  padding 6px 82px
  color: #05073b
  position relative

  display flex
  &.roleUser
    justify-content end
    .answerMain-item__avatar {
      left unset
      right 40px
    }
  &__avatar
    width 26px
    height 26px
    border-radius 50%
    position absolute
    top 12px
    left 40px
  &__content
    background: #fdfdfe;
    border-radius: 8px;
    box-shadow: 0 16px 20px 0 rgba(174,167,223,.06);
    display: flex;
    flex-direction: column;
    padding: 20px 28px;
    position: relative;
    font-size: 15px;
    line-height: 1.75;
    white-space: pre-line;
.answerMain-input
  background #fff
  display flex
  padding: 12px 28px 12px 12px;
  border-radius: 10px;
  box-shadow: 0 16px 20px 0 rgba(174, 167, 223, .2);
  min-height: 50px;
  &__textarea
    min-height: 50px;
    /deep/ .el-textarea__inner
      border none
      resize: none
      color: #05073b
  &__button
    font-size 16px
    padding 0 20px
    height 30px
    align-self end
</style>
